package com.cl.ks.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cl.ks.entity.KsDataType;
import com.cl.ks.entity.KsRule;
import com.cl.ks.entity.RlRuleTable;
import com.cl.ks.repository.KsRuleRepository;
import com.cl.ks.utils.QueryDslUtil;
import com.cl.mvc.service.BaseService;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.stereotype.Service;
import scala.annotation.meta.param;

import java.util.List;
import java.util.Optional;

import static com.cl.ks.constant.QTableConstant.*;

@Service
public class KsRuleService extends BaseService<KsRule> {
    private final JPAQueryFactory queryFactory;

    protected KsRuleService(KsRuleRepository KsRuleRepository, JPAQueryFactory queryFactory) {
        super(KsRuleRepository);
        this.queryFactory = queryFactory;
    }

    public KsRule editPower(KsRule param) {
        Optional<KsRule> ksRuleOptional = findById(param.getId());
        if (ksRuleOptional.isPresent()) {
            KsRule ksRule = ksRuleOptional.get();
            ksRule.setPower(param.getPower());
            return save(ksRule);
        }
        throw new RuntimeException("规则不存在");
    }

    public JSONArray exportKsRules(List<Integer> ids) {
        List<KsRule> ksRules = repository.findAllById(ids);
        return JSONArray.parseArray(JSONObject.toJSONString(ksRules));
    }

    public JSONObject ruleTypesGroupCount(List<String> ruleTypes, String auth) {
        JSONObject res = new JSONObject();

        String userId = String.valueOf(jwtUtil.getUserId(auth));
        String roleId = String.valueOf(jwtUtil.getRoleId(auth));
        String depId = String.valueOf(jwtUtil.getDepId(auth));
        BooleanExpression powerExpression = QueryDslUtil.generatePowerExpression(qKsRule, qKsRule.power, userId, roleId, depId);
        BooleanExpression tagsExpression = qKsRule.isNotNull().and(qKsRule.isNull());
        for (String ruleType : ruleTypes) {
            tagsExpression = tagsExpression.or(Expressions.asString(",").concat(qKsRule.ruleType).concat(",").contains(ruleType));
            res.put(ruleType, 0);
        }
        List<KsRule> ksRuleList = queryFactory.selectFrom(qKsRule).where(powerExpression.and(tagsExpression)).fetch();

        for (KsRule ksRule : ksRuleList) {
            String itemRuleType = "," + ksRule.getRuleType() + ",";
            for (String ruleType : ruleTypes) {
                if (itemRuleType.contains("," + ruleType + ",")) {
                    res.put(ruleType, res.getIntValue(ruleType) + 1);
                }
            }
        }
        return res;

    }

//    @Override
//    public Page<KsRule> page(KsRule entity, String auth) {
//        return repository.findAll(buildSpecification(entity).and(buildPowerSpecification(auth)), PageRequest.of(entity.getPageNumber() - 1, entity.getPageSize()));
//    }
}
